package com.op.teachingliteapp.database;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;

import com.op.teachingliteapp.BuildConfig;
import com.op.teachingliteapp.common.BaseApp;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.database.table.CourseNotifTable;
import com.op.teachingliteapp.database.table.CourseTable;
import com.op.teachingliteapp.database.table.SeminarTable;
import com.op.teachingliteapp.util.SharedPreferenceUtil;

/**
 * SQLiteOpenHelper
 * 
 * @author Michael
 * @date Jun 23, 2015
 */
public class DBHelper extends SQLiteOpenHelper {

	private static final String TAG = DBHelper.class.getSimpleName();

	private static final String DATABASE_PREFIX = "teachingliteapp";
	private static final int DATABASE_VERSION = 1;

	private static DBHelper instance;
	private static String userId;

	public static DBHelper getInstance() {
		SharedPreferences preferences = SharedPreferenceUtil.getInstance(BaseApp.getAppContext());
		String currentUserId = preferences.getString(Common.Prefs.USER_ID, "");
		if (TextUtils.isEmpty(userId)) {
			userId = currentUserId;
		} else if (userId != currentUserId) {
			synchronized (DBHelper.class) {
				instance = new DBHelper(BaseApp.getAppContext(), userId);
			}
		}
		if (instance == null) {
			synchronized (DBHelper.class) {
				if (instance == null) {
					instance = new DBHelper(BaseApp.getAppContext(), userId);
				}
			}
		}
		return instance;
	}

	public DBHelper(Context context, String userId) {
		this(context, DATABASE_PREFIX + userId + ".db", null, DATABASE_VERSION);
	}

	public DBHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		if (BuildConfig.DEBUG) {
			Log.d(TAG, "new DBHelper");
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		if (BuildConfig.DEBUG) {
			Log.d(TAG, "Creating database");
		}
		CourseTable.onCreate(db);
		CourseNotifTable.onCreate(db);
		SeminarTable.onCreate(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (BuildConfig.DEBUG) {
			Log.d(TAG, "Upgrading database");
		}
		CourseTable.onUpgrade(db, oldVersion, newVersion);
		CourseNotifTable.onUpgrade(db, oldVersion, newVersion);
		SeminarTable.onUpgrade(db, oldVersion, newVersion);
	}

}
